﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Data.OracleClient;
using System.IO;
using System.Configuration;
using UniversalPrinter;

namespace PrintService
{
    partial class PrintService : ServiceBase
    {
        int timerInterval;
        string logFile, selectSQL, updateSQL;
        OracleConnection connection = null;
        System.Timers.Timer processTimer;
        DocumentPrinter objPrint;

        public PrintService()
        {
            InitializeComponent();

            processTimer = new System.Timers.Timer();
            processTimer.Elapsed += new System.Timers.ElapsedEventHandler(processTimer_Elapsed);

            objPrint = new DocumentPrinter();
            objPrint.OnAfterSendPrinter += new EventHandler(objPrint_OnAfterSendPrinter);
        }

        private void objPrint_OnAfterSendPrinter(Object sender, System.EventArgs e)
        {
            using (OracleCommand command = connection.CreateCommand())
            {
                command.CommandText = updateSQL.Replace("[UniqueID]", ((DocumentPrinter)sender).UniqueID);
                command.CommandText = command.CommandText.Replace("[PrintResultText]", ((DocumentPrinter)sender).PrintResult.ToString());
                command.CommandText = command.CommandText.Replace("[PrintResultNumber]", ((byte)((DocumentPrinter)sender).PrintResult).ToString());
                command.ExecuteNonQuery();
            }
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                logFile = System.Reflection.Assembly.GetExecutingAssembly().Location + ".log";
                int.TryParse(ConfigurationManager.AppSettings["INTERVAL"], out timerInterval);
                updateSQL = ConfigurationManager.AppSettings["UPDATE_SQL"];
                selectSQL = ConfigurationManager.AppSettings["SELECT_SQL"];

                if (ConfigurationManager.AppSettings["SHOW_PRINTERS_ON_START"] == "1")
                {
                    objPrint.SavePrinterList(new FileInfo(logFile).DirectoryName + @"\PrinterList.txt");
                }

                processTimer.Interval = timerInterval;
                connection = new OracleConnection(ConfigurationManager.ConnectionStrings[0].ToString());

                connection.Open();
                processTimer.Enabled = true;
                processTimer.Start();
            }
            catch (Exception ex)
            {
                LogMessage(ex.Message);
            }
        }

        protected override void OnStop()
        {
            processTimer.Stop();
            connection.Dispose();
            objPrint.Dispose();
        }

        private void LogMessage(string message)
        {
            using (StreamWriter writer = new StreamWriter(logFile, true, Encoding.GetEncoding("windows-1254")))
            {
                writer.WriteLine(DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss") + "\t" + message);
            }
        }

        private void processTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                using (OracleCommand command = connection.CreateCommand())
                {
                    command.CommandText = selectSQL;
                    using (OracleDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            objPrint.Print(reader["DOSYA_AD"].ToString(), reader["PRINTER_AD"].ToString(), reader["PRINT_SEQ_NO"].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogMessage(ex.Message);
            }
        }
    }
}
